package com.leff.cards.request;

import com.leff.cards.Dictionary;
import com.leff.cards.StoreWrapper;
import com.leff.cards.entity.Group;
import com.leff.cards.entity.User;

public class InviteResponse extends Request {
	
	public InviteResponse(Dictionary dict) {
		super(dict);
	}
	
	public RequestResult doInviteResponse() {
		
		RequestResult result = this.verifyRequiredParameters(Parameter.GROUP_ID, Parameter.FB_ID, Parameter.JOIN);
		if(!result.isSuccessful()) {
			return result;
		}
		
		long groupId = Long.valueOf((String)mDictionary.get(Parameter.GROUP_ID));
		String idStr = (String)mDictionary.get(Parameter.FB_ID);
		long id = Long.parseLong(idStr);
		boolean join = mDictionary.get(Parameter.JOIN).toString().equals("1");
		
		Group G = StoreWrapper.getGroupById(groupId);
		if(G == null) {
			result.setErrorResult("No group found with ID " + groupId);
			return result;
		}
		
		User U = StoreWrapper.getUserByFbId(id);
		if(U == null) {
			result.setErrorResult("No user found with fbid " + id);
			return result;
		}

		StoreWrapper.deleteInvitation(groupId, id);
		
		if(join) {
			G.addMember(U);
			StoreWrapper.store(G);
			
			result.setSuccessMessage("Joined group " + G.getName());
		} else {
			result.setSuccessMessage("Declined invitation to " + G.getName());
		}
		
		return result;
	}
}
